package com.steakliu.sun.server.netty.manager;

import com.steakliu.sun.constant.SerializerConstant;
import com.steakliu.sun.protocol.MsgHeader;
import com.steakliu.sun.protocol.MsgType;
import com.steakliu.sun.protocol.SunProtocol;
import com.steakliu.sun.protocol.SunRequest;
import com.steakliu.sun.protocol.generate.MsgHeaderGenerator;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 功能说明： 连接管理器
 * <p>
 * Original @Author: steakliu-刘牌, 2023-02-01  17:13
 * <p>
 * Copyright (C)2020-2022  steakliu All rights reserved.
 */
public class ServerChannelManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerChannelManager.class);

    private static final Set<Channel> channels = new CopyOnWriteArraySet<>();

    public static void add(Channel channel){
        channels.add(channel);
    }

    public static void remove(Channel channel){
        channels.remove(channel);
    }

    /**
     * 扫除断开连接的channel
     */
    public static void scanNoteAliveChannel(){
        LOGGER.info("================扫描不活跃的channel并移除===================");
        channels.forEach(channel -> {
            if (!channel.isActive() && !channel.isOpen()){
                channel.close();
                channels.remove(channel);
            }
        });
    }

    public static void sendHeartBeatToChannel(){
        LOGGER.info("================向存活的channel发送心跳信息===================");
        SunProtocol<SunRequest> protocol = new SunProtocol<>();
        MsgHeader header = MsgHeaderGenerator.generateMsgHeader(SerializerConstant.JDK, MsgType.CLIENT_HEARTBEAT);
        SunRequest request = new SunRequest();
        request.setParameters(new Object[]{"client ping"});
        protocol.setMsgHeader(header);
        protocol.setBody(request);
        if (!channels.isEmpty()){
            channels.forEach(channel -> {
                if (!channel.isActive() && !channel.isOpen()){
                    channel.writeAndFlush(protocol);
                }
            });
        }
    }

}
